import { showToast, requestPayment } from '../../util/asyncWx'
import { request } from '../../request/index.js'
Page({
  data: {
    // 用户的收获地址
    address: {},
    // 购物车的数据
    carts: [],
    // 购物车选中总价格
    totalPrice: 0,
    // 购物车选中总数量
    totalNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onShow() {
    // 获取缓存中的收货地址信息
    const address = wx.getStorageSync('address')
    this.setData({
      address
    })
    // 获取缓存中的购物车数据
    let carts = wx.getStorageSync('carts') || []
    // 过滤后的 购物车 数据
    carts = carts.filter(v => v.checked)
    // 总价格和总数量
    let totalPrice = 0
    let totalNum = 0
    carts.forEach(item => {
      totalPrice += item.num * item.goods_price
      totalNum++
    });
    // 将值 给 data 中
    this.setData({
      carts,
      totalPrice,
      totalNum
    })
  },
  // 支付
  async handleOrderPay() {
    try {
      // 判断缓存中有没有 token
      const token = wx.getStorageSync("token")
      // 判断是否有 token 值
      if (!token) {
        wx.navigateTo({
          url: '/pages/auth/index',
        });
        return;
      }
      // 创建订单
      // 订单，准备请求头
      const header = { Authorization: token }
      // 订单，准备请求体参数
      const order_price = this.data.totalPrice;
      const consignee_addr = this.data.address.all
      const carts = this.data.carts
      let goods = []
      carts.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }))
      const orderParams = { order_price, consignee_addr, goods }
      // 发送订单请求,创建订单,获取订单编号
      const { data } = await request({ url: '/my/orders/create', data: orderParams, method: "POST", header })
      const order_number = data.message['order_number']
      // 发起 预支付
      const { data: { message: { pay } } } = await request({ url: '/my/orders/req_unifiedorder', method: "POST", header, data: { order_number } })
      // 发起微信支付
      console.log(pay);
      await requestPayment(pay)
      // 查询支付订单
      const res = await request({ url: '/my/orders/chkOrder', method: "POST", header, data: { order_number } });
      await showToast({title:'支付成功'})
      let newCarts = wx.getStorageSync('carts');
      newCarts = newCarts.filter(v=>!v.checked)
      wx.setStorageSync('carts',newCarts)
      wx.navigateTo({
        url: '/pages/order/index',
      })
    } catch (error) {
      await showToast({title:'支付失败'})
      console.log(error);
      wx.navigateTo({
        url: '/pages/order/index',
      })
    }
  }
})